/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.hiddendanger.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.hiddendanger.domain.CheckRecord;
import com.koron.hiddendanger.domain.PerformancePlan;
import com.koron.hiddendanger.mapper.CheckRecordMapper;
import com.koron.hiddendanger.mapper.PerformancePlanMapper;
import com.koron.system.domain.Message;
import com.koron.system.mapper.MessageMapper;
import org.koron.ebs.mybatis.SessionFactory;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class PerformancePlanJob implements Job {
    private final static Logger logger = LoggerFactory.getLogger(PerformancePlanJob.class);
    private final SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobDetail detail = context.getJobDetail();
        String id = detail.getJobDataMap().getString("id");
        SessionFactory factory = new SessionFactory();
        try {
            PerformancePlan plan = factory.getMapper(PerformancePlanMapper.class).queryOne(id);
            Date time = new Date();
            if (null != plan) {
                List<String> checkExecutors = JSONObject.parseArray(plan.getExecutors(), String.class);
                String taskName = "安全检查任务" + format.format(time);
                List<CheckRecord> recordList = new ArrayList<>();
                List<Message> messageList = new ArrayList<>();
                for (String checkExecutor : checkExecutors) {
                    try {
                        CheckRecord record = new CheckRecord();
                        Message message = new Message();
                        message.setId(DefaultIdGenerator.getInstance().generateLongId());
                        message.setAddTime(time);
                        message.setIsRemove(0);
                        message.setIsRead(0);
                        message.setAddUser(plan.getAddUser());
                        message.setUpdateUser(plan.getUpdateUser());
                        message.setUpdateTime(time);
                        message.setTitle("您有一项新的安全检查任务");
                        message.setId(DefaultIdGenerator.getInstance().generateLongId());
                        message.setContent("根据检查计划名称为：" + plan.getName() + "您有一项新的检查任务");
                        message.setReceiverCode(checkExecutor.split("_")[0]);
                        messageList.add(message);
                        record.setName(plan.getName());
                        record.setId(DefaultIdGenerator.getInstance().generateLongId());
                        record.setManager(checkExecutor.split("_")[0]);
                        record.setIdentifier(plan.getIdentifier());
                        record.setPlanId(plan.getId());
                        record.setCorpCode(plan.getCorpCode());
                        record.setGridCode(plan.getGridCode());
                        record.setCheckTime(compulateDeadline(plan.getRepeatType(), time));
                        recordList.add(record);
                    } catch (Exception e) {
                        logger.error(e.getMessage(),e);
                    }
                }
                if (null != recordList && recordList.size() > 0) {
                    factory.getMapper(CheckRecordMapper.class).batchInsertProduce(recordList);
                }
                if (null != messageList && messageList.size() > 0) {
                    factory.getMapper(MessageMapper.class).batchInsert(messageList);
                }
                factory.close();
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            factory.close(false);
        }finally {
            factory.close();
        }
    }

    private Date compulateDeadline(Integer repeatType, Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        switch (repeatType) {
            case 0:
                calendar.add(Calendar.DAY_OF_WEEK, 7);
                break;
            case 1:
                calendar.add(Calendar.MONTH, 1);
                break;
            case 2:
                calendar.add(Calendar.MONTH, 3);
                break;
            case 3:
                calendar.add(Calendar.MONTH, 6);
                break;
            case 4:
                calendar.add(Calendar.YEAR, 1);
                break;
            case 5:
                break;

            default:
                break;
        }
        return calendar.getTime();
    }
}
